package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("新增菜品成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo =new Page<>(page,pageSize);
        //将菜品分类id转为菜品分类名称
        Page<DishDto>  dishDtoPage=new Page<>();
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,lqw);
        //将pageInfo中的对象拷贝到dishDtoPage中
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list =records.stream().map((item)->{
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.upDateWithFlavor(dishDto);
        //菜品信息更新后，清楚该菜品id对应的key
        Set keys=redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("菜品信息修改成功");
    }
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //动态构造一个唯一的key
        /*String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //在redis库中查找是否存在该key
//        Object o = redisTemplate.opsForValue().get(key);
//        String str = JSON.toJSONString(redisTemplate.opsForValue().get(key));
//        String s = StringEscapeUtils.unescapeJava(str);
//        List<DishDto> dishDtoList = JSON.parseObject(s, new TypeReference<ArrayList<DishDto>>(){});
        List<DishDto> dishDtoList  = new Gson().fromJson(new Gson().toJson(redisTemplate.opsForValue().get(key)), new TypeToken<List<DishDto>>(){}.getType());
        if(dishDtoList!=null){
            return R.success(dishDtoList);
        }*/
        List<DishDto> dishDtoList = null;
//动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();//dish_1397844391040167938_1
//先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId())
                .orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishService.list(lqw);
        //此时还无法显示菜品口味信息，需要用dto对象进行封装
        dishDtoList=dishList.stream().map((item)->{
            //此时item均为dish对象，需要挨个将其装入dishDto之中
            DishDto dishDto=new DishDto();
            //拷贝基本信息
            BeanUtils.copyProperties(item,dishDto);
            Long dishId = item.getId();
            //根据dishId在口味表中查找口味信息
            LambdaQueryWrapper<DishFlavor> lqw2=new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavors = dishFlavorService.list(lqw2);
            dishDto.setFlavors(dishFlavors);
            return dishDto;
        }).collect(Collectors.toList());
        /*if (dishDtoList.size()!=0){
            redisTemplate.opsForValue().set(key,new Gson().toJson(dishDtoList),60, TimeUnit.MINUTES);
            return R.success(dishDtoList);
        }else{
            return R.error("当前分类无数据");
        }*/
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
    @PostMapping("/status/{st}")
    public R<String> updateStatus(@PathVariable int st,@RequestParam List<Long> ids){
        //批量操作，接收id数组，遍历该数组，查看各个菜品状态
        List<Dish> dishes = dishService.listByIds(ids);
        dishes.stream().forEach(dish->{
            dish.setStatus(st);
        });
        dishService.updateBatchById(dishes);
        return R.success("修改状态成功");
    }
    @DeleteMapping
    public R<String> delete(Long[] ids){
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            if(dish.getStatus()==1){
                return R.error("已启售菜品无法删除");
            }
            //删除菜品信息前，需要删除对应的口味信息
            LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(lqw);
            dishService.removeById(id);
        }
        return R.success("删除成功");
    }
}
